<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form layout="vertical" ref="formRef" :model="formState" :rules="rules">
        <div class="option-column">
          <div class="column-title">基础信息</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="名称" name="name">
                <a-input
                  v-model:value="formState.name"
                  placeholder="请输入名称"
                />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="分类" name="instrument_category_id">
                <a-select
                  v-model:value="formState.instrument_category_id"
                  placeholder="请选择分类"
                >
                  <a-select-option
                    v-for="option in categoryOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </div>
            <!-- <div class="content-item">
              <a-form-item label="背景音乐" name="music_url">
                <a-input
                  v-model:value="formState.music_url"
                  placeholder="请输入上传背景音乐"
                  readyonly
                >
                  <template #suffix>
                      <info-circle-outlined
                        style="color: rgba(0, 0, 0, 0.45)"
                      />
                  </template>
                </a-input>
              </a-form-item>
            </div> -->
            <div class="content-item">
              <a-form-item label="企业信息">
                <a-input
                  v-model:value="formState.company_info"
                  placeholder="请输入企业信息"
                >
                </a-input>
              </a-form-item>
            </div>
          </div>
        </div>

        <div class="option-column">
          <div class="column-title">背景音乐</div>
          <a-upload-dragger
            v-model:fileList="musicFileList"
            name="file"
            :multiple="false"
            :max-count="1"
            accept="audio/*"
            :customRequest="customUploadMusic"
            @change="handleChangeMusic"
            @drop="handleDropMusic"
          >
            <p class="ant-upload-drag-icon">
              <CloudUploadOutlined />
            </p>
            <p class="ant-upload-hint">
              将mp3、wav、ogg格式的音频文件拖拽到此，或单击<span class="blue"
                >直接上传</span
              >支持常见音频格式
            </p>
          </a-upload-dragger>
        </div>
        <div class="option-column">
          <div class="column-title">模型与略缩图</div>
          <div class="column-form">
            <div class="column-form-title">模型</div>
            <div class="column-form-value">
              <a-upload-dragger
                v-model:fileList="modelFileList"
                name="file"
                :multiple="false"
                :max-count="1"
                :customRequest="customUploadModel"
                @change="handleChangeModel"
                @drop="handleDropModel"
              >
                <p class="ant-upload-drag-icon">
                  <CloudUploadOutlined />
                </p>
                <p class="ant-upload-hint">
                  将模型拖拽到此，或单击<span class="blue">直接上传</span>
                </p>
              </a-upload-dragger>
            </div>
          </div>
          <div class="column-form">
            <div class="column-form-title">略缩图</div>
            <div class="column-form-value">
              <a-upload-dragger
                v-model:fileList="thumbnailFileList"
                name="file"
                :multiple="false"
                :max-count="1"
                :customRequest="customUploadThumbnail"
                @change="handleChangeThumbnail"
                @drop="handleDropThumbnail"
              >
                <p class="ant-upload-drag-icon">
                  <CloudUploadOutlined />
                </p>
                <p class="ant-upload-hint">
                  将jpg、bmp、png格式的图片拖拽到此，或单击<span class="blue"
                    >直接上传</span
                  >分辨建议为400*300
                </p>
              </a-upload-dragger>
            </div>
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">介绍内容</div>
          <div class="column-form">
            <div class="column-form-title">仪器介绍</div>
            <div class="content-value">
              <edit v-model:value="introduction" />
            </div>
          </div>
          <div class="column-form">
            <div class="column-form-title">实验内容</div>
            <div class="content-value">
              <edit v-model:value="content" />
            </div>
          </div>
          <div class="column-form">
            <div class="column-form-title">配置参数</div>
            <div class="content-value">
              <edit v-model:value="remark" />
            </div>
          </div>
        </div>
        <div class="option-footer">
          <a-button class="opt-btn" @click="resetForm">取消</a-button>
          <a-button class="opt-btn" type="primary" @click="saveInstrument"
            >保存</a-button
          >
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, h, watch, onMounted } from "vue";
import {
  PlusOutlined,
  MinusCircleOutlined,
  CloudUploadOutlined,
} from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import administratorApi from "@/api/administrator";
import systemApi from "@/api/system";
import operationApi from "@/api/operation";
import edit from "@/components/edit/index.vue";

const route = useRoute();
const router = useRouter();
const isEdit = ref(false);
const instrumentId = ref(null);
const formState = ref({
  name: "",
  limt: "",
  remark: "",
  status: [],
  company_info: "天津良益科技股份有限公司",
  instrument_category_id: null,
  music_url: "", // 新增背景音乐URL参数
});

const configurationList = ref([
  {
    configurationName: "",
    configurationParameter: "",
  },
]);
const content = ref("");
const introduction = ref("");
const remark = ref("");

// 设备状态选项
const deviceStatusOptions = ref([]);
// 仪器分类选项
const categoryOptions = ref([]);

// 获取仪器分类选项
const fetchCategoryOptions = async () => {
  try {
    const res = await administratorApi.InstrumentCategoryOptions({});
    if (res) {
      categoryOptions.value = res.map((item) => ({
        label: item.text,
        value: item.value,
      }));
    }
  } catch (error) {
    console.error("获取仪器分类选项失败", error);
    message.error("获取仪器分类选项失败");
  }
};

// 获取仪器详情（编辑模式）
const fetchInstrumentDetail = async () => {
  if (!instrumentId.value) return;

  try {
    const res = await administratorApi.InstrumentDetail({
      instrument_id: instrumentId.value,
    });

    if (res && res) {
      const data = res;
      formState.value = {
        name: data.name || "",
        limt: data.warranty_period || "",
        // remark: data.remark || "",
        status: data.enabled ? "enabled" : "disabled",
        company_info: data.company_info || "天津良益科技股份有限公司",
        music_url: data.music_url || "", // 添加背景音乐URL
        instrument_category_id: data.instrument_category_id,
      };
      content.value = (data.experiment || "")
        .replace(/\r\n/g, "\n")
        .replace(/\r/g, "\n");
      introduction.value = (data.introduce || "")
        .replace(/\r\n/g, "\n")
        .replace(/\r/g, "\n");
      remark.value = (data.remark || "")
        .replace(/\r\n/g, "\n")
        .replace(/\r/g, "\n");

      // 如果有配置参数，也需要填充
      // if (data.configurations && data.configurations.length > 0) {
      //   configurationList.value = data.configurations.map((config) => ({
      //     configurationName: config.name || "",
      //     configurationParameter: config.parameter || "",
      //   }));
      // }

      // 设置文件列表 - 确保回显正常
      if (data.model_url) {
        modelFileList.value = [
          {
            uid: "model-1",
            name: "设备模型文件",
            status: "done",
            url: data.model_url,
          },
        ];
      }

      if (data.thumb_url) {
        thumbnailFileList.value = [
          {
            uid: "thumbnail-1",
            name: "缩略图",
            status: "done",
            url: data.thumb_url,
          },
        ];
      }

      // 设置背景音乐文件列表
      if (data.music_url) {
        musicFileList.value = [
          {
            uid: "music-1",
            name: "背景音乐",
            status: "done",
            url: data.music_url,
          },
        ];
      }
    } else {
      message.error(res?.errors || "获取设备详情失败");
    }
  } catch (error) {
    console.error("获取设备详情失败", error);
    message.error("获取设备详情失败");
  }
};

// 获取缩略图URL
const getThumbnailUrl = () => {
  if (thumbnailFileList.value.length > 0) {
    const file = thumbnailFileList.value[0];
    return file.response?.data?.url || file.url || "";
  }
  return "";
};

// 获取模型文件URL
const getModelFileUrl = () => {
  if (modelFileList.value.length > 0) {
    const file = modelFileList.value[0];
    return file.response?.data?.url || file.url || "";
  }
  return "";
};

// 获取背景音乐URL
const getMusicUrl = () => {
  if (musicFileList.value.length > 0) {
    const file = musicFileList.value[0];
    return file.response?.data?.url || file.url || "";
  }
  return "";
};
const formRef = ref(null);
// 保存仪器信息
const saveInstrument = async () => {
  if (!formState.value.name) {
    message.error("名称不能为空");
    return;
  }

  try {
    const params = {
      name: formState.value.name,
      warranty_period: formState.value.limt,
      remark: remark.value,
      enabled: formState.value.status === "enabled",
      instrument_category_id: Number(formState.value.instrument_category_id),
      company_info: formState.value.company_info,
      experiment: content.value,
      introduce: introduction.value,
      thumb_url: getThumbnailUrl(),
      model_url: getModelFileUrl(),
      music_url: getMusicUrl(), // 添加背景音乐URL参数
      // configurations: configurationList.value.filter(
      //   (item) => item.configurationName || item.configurationParameter
      // ),
    };

    if (isEdit.value) {
      params.instrument_id = instrumentId.value;
      const res = await administratorApi.InstrumentUpdate(params);
      if (res) {
        message.success("更新成功");
        router.go(-1);
      } else {
        message.error(res?.errors || "更新失败");
      }
    } else {
      params.instrument_id = 'tmpId';
      const res = await administratorApi.InstrumentCreate(params);
      if (res) {
        message.success("创建成功");
        router.go(-1);
      } else {
        message.error(res?.errors || "创建失败");
      }
    }
  } catch (error) {
    console.error("保存失败", error);
    message.error("保存失败");
  }
};

const resetForm = () => {
  router.go(-1);
};
const addDevice = () => {
  configurationList.value.push({
    configurationName: "",
    configurationParameter: "",
  });
};

const deleteDevice = (index) => {
  configurationList.value.splice(index, 1);
};
// 文件列表 - 使用更清晰的命名
const modelFileList = ref([]); // 模型文件列表
const thumbnailFileList = ref([]); // 缩略图文件列表
const musicFileList = ref([]); // 背景音乐文件列表

// 自定义上传函数 - 设备模型
const customUploadModel = async (options) => {
  const { file, onSuccess, onError, onProgress } = options;

  try {
    onProgress({ percent: 50 });
    const response = await systemApi.FileUpload(file);
    console.log("模型文件上传响应:", response);

    // 适配实际的API响应格式
    if (response && response.url) {
      // 构造符合Ant Design Upload组件期望的响应格式
      const formattedResponse = {
        succeeded: true,
        data: {
          url: response.url.trim().replace(/`/g, ""), // 去除URL中的反引号和空格
          file_id: response.file_id,
          file_name: response.file_name,
          file_size: response.file_size,
          file_content_type: response.file_content_type,
        },
      };
      console.log("格式化后的响应:", formattedResponse);
      onSuccess(formattedResponse, file);
    } else {
      console.error("API响应格式错误:", response);
      onError(new Error("上传失败：响应格式错误"));
    }
  } catch (error) {
    console.error("模型文件上传失败:", error);
    onError(error);
  }
};

const handleChangeModel = (info) => {
  const { fileList } = info;
  modelFileList.value = fileList;

  const status = info.file.status;
  console.log("=== 模型文件上传状态详情 ===");
  console.log("文件状态:", status);
  console.log("文件名:", info.file.name);
  console.log("文件大小:", info.file.size);
  console.log("响应数据:", info.file.response);
  console.log("文件URL:", info.file.url);
  console.log("完整文件对象:", info.file);
  console.log("文件列表:", fileList);
  console.log("================================");

  if (status === "done") {
    // 处理上传成功的响应数据
    const response = info.file.response;
    console.log("处理上传成功响应:", response);

    if (response && response.succeeded && response.data) {
      // 更新文件信息，使用API返回的URL
      info.file.url = response.data.url;
      console.log("设置文件URL为:", response.data.url);
      message.success(`${info.file.name} 模型文件上传成功`);
    } else {
      console.error("响应格式错误:", response);
      message.error(`${info.file.name} 模型文件上传失败`);
    }
  } else if (status === "error") {
    console.error("上传错误:", info.file.error);
    message.error(`${info.file.name} 模型文件上传失败`);
  }
};

function handleDropModel(e) {
  console.log("模型文件拖拽:", e);
}

// 自定义上传函数 - 缩略图
const customUploadThumbnail = async (options) => {
  const { file, onSuccess, onError, onProgress } = options;

  try {
    onProgress({ percent: 50 });
    const response = await systemApi.FileUpload(file);
    console.log("缩略图上传响应:", response);

    // 适配实际的API响应格式
    if (response && response.url) {
      // 构造符合Ant Design Upload组件期望的响应格式
      const formattedResponse = {
        succeeded: true,
        data: {
          url: response.url.trim().replace(/`/g, ""), // 去除URL中的反引号和空格
          file_id: response.file_id,
          file_name: response.file_name,
          file_size: response.file_size,
          file_content_type: response.file_content_type,
        },
      };
      console.log("格式化后的响应:", formattedResponse);
      onSuccess(formattedResponse, file);
    } else {
      console.error("API响应格式错误:", response);
      onError(new Error("上传失败：响应格式错误"));
    }
  } catch (error) {
    console.error("缩略图上传失败:", error);
    onError(error);
  }
};

const handleChangeThumbnail = (info) => {
  const { fileList } = info;
  thumbnailFileList.value = fileList;

  const status = info.file.status;
  console.log("=== 缩略图上传状态详情 ===");
  console.log("文件状态:", status);
  console.log("文件名:", info.file.name);
  console.log("文件大小:", info.file.size);
  console.log("响应数据:", info.file.response);
  console.log("文件URL:", info.file.url);
  console.log("完整文件对象:", info.file);
  console.log("文件列表:", fileList);
  console.log("================================");

  if (status === "done") {
    // 处理上传成功的响应数据
    const response = info.file.response;
    console.log("处理上传成功响应:", response);

    if (response && response.succeeded && response.data) {
      // 更新文件信息，使用API返回的URL
      info.file.url = response.data.url;
      console.log("设置文件URL为:", response.data.url);
      message.success(`${info.file.name} 缩略图上传成功`);
    } else {
      console.error("响应格式错误:", response);
      message.error(`${info.file.name} 缩略图上传失败`);
    }
  } else if (status === "error") {
    console.error("上传错误:", info.file.error);
    message.error(`${info.file.name} 缩略图上传失败`);
  }
};

function handleDropThumbnail(e) {
  console.log("缩略图拖拽:", e);
}

// 自定义上传函数 - 背景音乐
const customUploadMusic = async (options) => {
  const { file, onSuccess, onError, onProgress } = options;

  try {
    onProgress({ percent: 50 });
    const response = await systemApi.FileUpload(file);
    console.log("背景音乐上传响应:", response);

    // 适配实际的API响应格式
    if (response && response.url) {
      // 构造符合Ant Design Upload组件期望的响应格式
      const formattedResponse = {
        succeeded: true,
        data: {
          url: response.url.trim().replace(/`/g, ""), // 去除URL中的反引号和空格
          file_id: response.file_id,
          file_name: response.file_name,
          file_size: response.file_size,
          file_content_type: response.file_content_type,
        },
      };
      console.log("格式化后的响应:", formattedResponse);
      onSuccess(formattedResponse, file);
    } else {
      console.error("API响应格式错误:", response);
      onError(new Error("上传失败：响应格式错误"));
    }
  } catch (error) {
    console.error("背景音乐上传失败:", error);
    onError(error);
  }
};
const fileListMusic = ref([]);
const handleChangeMusic = (info) => {
  const { fileList } = info;
  fileListMusic.value = fileList;

  const status = info.file.status;
  console.log("=== 背景音乐上传状态详情 ===");
  console.log("文件状态:", status);
  console.log("文件名:", info.file.name);
  console.log("文件大小:", info.file.size);
  console.log("响应数据:", info.file.response);
  console.log("文件URL:", info.file.url);
  console.log("完整文件对象:", info.file);
  console.log("文件列表:", fileList);
  console.log("================================");

  if (status === "done") {
    // 处理上传成功的响应数据
    const response = info.file.response;
    console.log("处理上传成功响应:", response);

    if (response && response.succeeded && response.data) {
      // 更新文件信息，使用API返回的URL
      info.file.url = response.data.url;
      console.log("设置文件URL为:", response.data.url);
      // 同时更新 formState 中的 music_url
      formState.value.music_url = response.data.url;
      message.success(`${info.file.name} 背景音乐上传成功`);
    } else {
      console.error("响应格式错误:", response);
      message.error(`${info.file.name} 背景音乐上传失败`);
    }
  } else if (status === "error") {
    console.error("上传错误:", info.file.error);
    message.error(`${info.file.name} 背景音乐上传失败`);
  }
};

function handleDropMusic(e) {
  console.log("背景音乐拖拽:", e);
}
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入设备名称",
      trigger: "blur",
    },
  ],
});

// 初始化
onMounted(() => {
  // 获取设备状态选项
  // fetchDeviceStatusOptions();
  // 获取仪器分类选项
  fetchCategoryOptions();

  // 检查是否为编辑模式
  if (route.query.instrument_id) {
    isEdit.value = true;
    instrumentId.value = route.query.instrument_id;
    fetchInstrumentDetail();
  }
});
</script>
